package com.och.mrcp.service.impl;

import com.alibaba.nls.client.protocol.NlsClient;
import com.och.mrcp.config.EngineConfig;
import com.och.mrcp.core.rtp.session.RtpSession;
import com.och.mrcp.model.SynthesisResult;
import com.och.mrcp.service.TtsSynthesisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Slf4j
@Service("aliyunTtsSynthesisService")
@RequiredArgsConstructor
public class AliyunTtsSynthesisService implements TtsSynthesisService {

	private final AliyunVoiceSessionService aliyunVoiceSessionService;

	@Override
	public String getProviderName() {
		return "aliyun";
	}

	@Override
	public boolean isAvailable() {
		return aliyunVoiceSessionService.isAvailable();
	}

	@Override
	public CompletableFuture<SynthesisResult> synthesize(String sessionId, String text, EngineConfig.SynthesisConfig config, RtpSession rtpSession) {
		try {
			if (!isAvailable()) {
				return CompletableFuture.failedFuture(new IllegalStateException("Aliyun TTS not available"));
			}
			String appKey = aliyunVoiceSessionService.getEngineConfig().getAliyun().getAppKey();
			if (appKey == null || appKey.isEmpty()) {
				return CompletableFuture.failedFuture(new IllegalStateException("Aliyun AppKey is not configured"));
			}
			NlsClient nlsClient = aliyunVoiceSessionService.getNlsClient();
			AliyunTtsSession ttsSession = new AliyunTtsSession(
					sessionId,
					appKey,
					nlsClient,
					config,
					rtpSession
			);
			return ttsSession.startSynthesis(text);
		} catch (Exception e) {
			log.error("Aliyun synthesize failed for session {}", sessionId, e);
			return CompletableFuture.failedFuture(e);
		}
	}
}


